<template>
  <div class="resource-registry">
    <div class="page-header">
      <h2>资源注册中心</h2>
      <a-button type="primary" @click="openCreateModal"> 创建资源 </a-button>
    </div>

    <!-- 搜索和筛选 -->
    <a-card style="margin-bottom: 16px">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="关键词">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="搜索资源名称或描述"
            style="width: 200px"
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="资源类型">
          <a-select
            v-model:value="searchForm.type"
            placeholder="选择类型"
            style="width: 150px"
            allow-clear
          >
            <a-select-option value="PHYSICAL">物理资源</a-select-option>
            <a-select-option value="DIGITAL">数字资源</a-select-option>
            <a-select-option value="HUMAN">人力资源</a-select-option>
            <a-select-option value="SERVICE">服务资源</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="业务类型">
          <a-select
            v-model:value="searchForm.category"
            placeholder="选择业务类型"
            style="width: 150px"
            allow-clear
          >
            <a-select-option value="HOTEL">酒店</a-select-option>
            <a-select-option value="APARTMENT">公寓</a-select-option>
            <a-select-option value="SPA">温泉</a-select-option>
            <a-select-option value="SCENIC">景区</a-select-option>
            <a-select-option value="RESTAURANT">餐饮</a-select-option>
            <a-select-option value="MEDICAL_BEAUTY">医美</a-select-option>
            <a-select-option value="BEAUTY_SALON">美容美发</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="选择状态"
            style="width: 120px"
            allow-clear
          >
            <a-select-option value="1">激活</a-select-option>
            <a-select-option value="0">停用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch"> 搜索 </a-button>
            <a-button @click="handleReset"> 重置 </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 资源列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="resourceList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeLabel(record.type) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'category'">
            <a-tag :color="getCategoryColor(record.category)">
              {{ getCategoryLabel(record.category) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '激活' : '停用' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="viewResource(record)">查看</a>
              <a @click="editResource(record)">编辑</a>
              <a @click="viewPricing(record)">定价</a>
              <a @click="viewCapabilities(record)">能力</a>
              <a-popconfirm
                title="确定要删除这个资源吗？"
                @confirm="deleteResource(record.id)"
              >
                <a class="text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑资源模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      width="1000px"
      @ok="handleSubmit"
      @cancel="handleCancel"
    >
      <a-form :model="formData" layout="vertical">
        <a-tabs v-model:activeKey="activeTab">
          <a-tab-pane key="basic" tab="基本信息">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="资源名称" name="name" required>
                  <a-input
                    v-model:value="formData.name"
                    placeholder="请输入资源名称"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="资源代码" name="code" required>
                  <a-input
                    v-model:value="formData.code"
                    placeholder="请输入资源代码"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="资源类型" name="resource_type" required>
                  <a-select
                    v-model:value="formData.resource_type"
                    placeholder="选择资源类型"
                    @change="handleResourceTypeChange"
                  >
                    <a-select-option value="PHYSICAL">物理资源</a-select-option>
                    <a-select-option value="DIGITAL">数字资源</a-select-option>
                    <a-select-option value="HUMAN">人力资源</a-select-option>
                    <a-select-option value="SERVICE">服务资源</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="资源子类型" name="resource_sub_type">
                  <a-select
                    v-model:value="formData.resource_sub_type"
                    placeholder="选择资源子类型"
                  >
                    <a-select-option
                      v-for="option in subTypeOptions"
                      :key="option.value"
                      :value="option.value"
                    >
                      {{ option.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="业务类型" name="business_type" required>
                  <a-select
                    v-model:value="formData.business_type"
                    placeholder="选择业务类型"
                  >
                    <a-select-option value="HOTEL">酒店</a-select-option>
                    <a-select-option value="APARTMENT">公寓</a-select-option>
                    <a-select-option value="SPA">温泉</a-select-option>
                    <a-select-option value="SCENIC">景区</a-select-option>
                    <a-select-option value="RESTAURANT">餐饮</a-select-option>
                    <a-select-option value="MEDICAL_BEAUTY"
                      >医美</a-select-option
                    >
                    <a-select-option value="BEAUTY_SALON"
                      >美容美发</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="状态" name="status">
                  <a-select
                    v-model:value="formData.status"
                    placeholder="选择状态"
                  >
                    <a-select-option value="1">激活</a-select-option>
                    <a-select-option value="0">停用</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item label="描述" name="description">
              <a-textarea
                v-model:value="formData.description"
                :rows="3"
                placeholder="请输入资源描述"
              />
            </a-form-item>
          </a-tab-pane>

          <a-tab-pane key="properties" tab="属性配置">
            <a-form-item label="属性配置" name="properties">
              <a-textarea
                v-model:value="formData.properties"
                :rows="8"
                placeholder="请输入JSON格式的属性配置"
              />
            </a-form-item>
          </a-tab-pane>

          <a-tab-pane key="constraints" tab="约束条件">
            <a-form-item label="约束条件" name="constraints">
              <a-textarea
                v-model:value="formData.constraints"
                :rows="8"
                placeholder="请输入JSON格式的约束条件"
              />
            </a-form-item>
          </a-tab-pane>

          <a-tab-pane key="metadata" tab="元数据">
            <a-form-item label="元数据" name="metadata">
              <a-textarea
                v-model:value="formData.metadata"
                :rows="8"
                placeholder="请输入JSON格式的元数据"
              />
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-modal>

    <!-- 资源详情模态框 -->
    <a-modal
      v-model:open="detailVisible"
      title="资源详情"
      width="1200px"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="资源名称">{{
          detailData.name
        }}</a-descriptions-item>
        <a-descriptions-item label="资源代码">{{
          detailData.code
        }}</a-descriptions-item>
        <a-descriptions-item label="资源类型">{{
          detailData.resource_type_name
        }}</a-descriptions-item>
        <a-descriptions-item label="资源子类型">{{
          detailData.resource_sub_type_name
        }}</a-descriptions-item>
        <a-descriptions-item label="业务类型">{{
          detailData.business_type_name
        }}</a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="detailData.status === 1 ? 'green' : 'red'">
            {{ detailData.status === 1 ? '激活' : '停用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="描述" :span="2">{{
          detailData.description
        }}</a-descriptions-item>
        <a-descriptions-item label="创建时间">{{
          detailData.create_time
        }}</a-descriptions-item>
        <a-descriptions-item label="更新时间">{{
          detailData.update_time
        }}</a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <a-tabs>
        <a-tab-pane key="properties" tab="属性配置">
          <pre>{{ formatJson(detailData.properties) }}</pre>
        </a-tab-pane>
        <a-tab-pane key="capabilities" tab="能力配置">
          <pre>{{ formatJson(detailData.capabilities) }}</pre>
        </a-tab-pane>
        <a-tab-pane key="constraints" tab="约束条件">
          <pre>{{ formatJson(detailData.constraints) }}</pre>
        </a-tab-pane>
        <a-tab-pane key="metadata" tab="元数据">
          <pre>{{ formatJson(detailData.metadata) }}</pre>
        </a-tab-pane>
        <a-tab-pane key="trading" tab="交易信息">
          <pre>{{ formatJson(detailData.trading) }}</pre>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import { getResources } from '#/api/resource-center';
import { useRouter } from 'vue-router';

const router = useRouter();

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const detailVisible = ref(false);
const isEdit = ref(false);
const currentId = ref('');
const activeTab = ref('basic');

const searchForm = reactive({
  keyword: '',
  type: '',
  category: '',
  status: '',
});

const formData = reactive({
  name: '',
  code: '',
  resource_type: '',
  resource_sub_type: '',
  business_type: '',
  status: '1',
  description: '',
  properties: '',
  constraints: '',
  metadata: '',
});

const detailData = reactive({
  name: '',
  code: '',
  resource_type_name: '',
  resource_sub_type_name: '',
  business_type_name: '',
  status: 1,
  description: '',
  create_time: '',
  update_time: '',
  properties: '',
  capabilities: '',
  constraints: '',
  metadata: '',
  trading: '',
});

const resourceList = ref([]);

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
});

const columns = [
  {
    title: '资源名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '资源代码',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '资源类型',
    dataIndex: 'resource_type_name',
    key: 'resource_type_name',
  },
  {
    title: '业务类型',
    dataIndex: 'business_type_name',
    key: 'business_type_name',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    key: 'create_time',
  },
  {
    title: '操作',
    key: 'action',
    width: 300,
  },
];

// 计算属性
const modalTitle = computed(() => (isEdit.value ? '编辑资源' : '创建资源'));

// 资源子类型选项
const subTypeOptions = computed(() => {
  const typeMap = {
    PHYSICAL: [
      { value: 'BUILDING', label: '建筑物' },
      { value: 'FLOOR', label: '楼层' },
      { value: 'ROOM', label: '客房' },
      { value: 'RESORT', label: '度假村' },
      { value: 'SCENIC', label: '景区' },
      { value: 'RESTAURANT', label: '餐厅' },
      { value: 'MEDICAL', label: '医疗机构' },
      { value: 'SALON', label: '沙龙' },
    ],
    DIGITAL: [
      { value: 'SOFTWARE', label: '软件' },
      { value: 'API', label: 'API接口' },
      { value: 'DATABASE', label: '数据库' },
      { value: 'SERVICE', label: '服务' },
    ],
    HUMAN: [
      { value: 'TEAM', label: '团队' },
      { value: 'INDIVIDUAL', label: '个人' },
      { value: 'EXPERT', label: '专家' },
    ],
    SERVICE: [
      { value: 'BUSINESS', label: '业务服务' },
      { value: 'TECHNICAL', label: '技术服务' },
      { value: 'CONSULTING', label: '咨询服务' },
    ],
  };
  return typeMap[formData.resource_type] || [];
});

// 格式化JSON显示
const formatJson = (jsonString: string) => {
  try {
    if (!jsonString) return '';
    const parsed =
      typeof jsonString === 'string' ? JSON.parse(jsonString) : jsonString;parsedtypeofjsonStringJSON.parseparsedtypeofjsonStringJSON.parse
    return JSON.stringify(parsed, null, 2);
  } catch (error) {
    return jsonString || '';
  }
};

// 处理资源类型变化
const handleResourceTypeChange = () => {
  formData.resource_sub_type = '';
};

// 获取类型颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    entity: 'blue',
    service: 'green',
    capability: 'purple',
  };
  return colorMap[type] || 'default';
};

// 获取类型标签
const getTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    entity: '实体',
    service: '服务',
    capability: '能力',
  };
  return labelMap[type] || type;
};

// 获取分类颜色
const getCategoryColor = (category: string) => {
  const colorMap: Record<string, string> = {
    hotel: 'blue',
    pet: 'green',
    education: 'purple',
    retail: 'orange',
  };
  return colorMap[category] || 'default';
};

// 获取分类标签
const getCategoryLabel = (category: string) => {
  const labelMap: Record<string, string> = {
    hotel: '酒店',
    pet: '宠物',
    education: '教育',
    retail: '零售',
  };
  return labelMap[category] || category;
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: 'green',
    draft: 'orange',
    inactive: 'red',
  };
  return colorMap[status] || 'default';
};

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    active: '激活',
    draft: '草稿',
    inactive: '停用',
  };
  return labelMap[status] || status;
};

// 加载资源列表
const loadResourceList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      resource_type: searchForm.type,
      business_type: searchForm.category,
      status: searchForm.status,
    };

    const result = await getResources(params);
    resourceList.value = result.items;
    pagination.total = result.total;
  } catch (error) {
    message.error('加载资源列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadResourceList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    type: '',
    category: '',
    status: '',
  });
  pagination.current = 1;
  loadResourceList();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadResourceList();
};

// 打开创建模态框
const openCreateModal = () => {
  isEdit.value = false;
  currentId.value = '';
  resetForm();
  modalVisible.value = true;
};

// 编辑资源
const editResource = (record: any) => {
  isEdit.value = true;
  currentId.value = record.id;
  modalVisible.value = true;

  Object.assign(formData, {
    name: record.name,
    code: record.code,
    resource_type: record.resource_type,
    resource_sub_type: record.resource_sub_type,
    business_type: record.business_type,
    status: record.status.toString(),
    description: record.description,
    properties: record.properties,
    constraints: record.constraints,
    metadata: record.metadata,
  });
};

// 查看资源
const viewResource = (record: any) => {
  Object.assign(detailData, {
    name: record.name,
    code: record.code,
    resource_type_name: record.resource_type_name,
    resource_sub_type_name: record.resource_sub_type_name,
    business_type_name: record.business_type_name,
    status: record.status,
    description: record.description,
    create_time: record.create_time,
    update_time: record.update_time,
    properties: record.properties,
    capabilities: record.capabilities,
    constraints: record.constraints,
    metadata: record.metadata,
    trading: record.trading,
  });
  detailVisible.value = true;
};

// 查看定价
const viewPricing = (record: any) => {
  message.info(`查看定价: ${record.name}`);
  // 这里可以跳转到定价配置页面
};

// 查看能力
const viewCapabilities = (record: any) => {
  message.info(`查看能力: ${record.name}`);
  // 这里可以跳转到能力配置页面
};

// 删除资源
const deleteResource = async (id: string) => {
  try {
    message.success('删除成功');
    loadResourceList();
  } catch (error) {
    message.error('删除失败');
    console.error(error);
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    if (isEdit.value) {
      message.success('更新成功');
      modalVisible.value = false;
      loadResourceList();
    } else {
      message.success('创建成功');
      modalVisible.value = false;
      loadResourceList();
    }
  } catch (error) {
    message.error('操作失败');
    console.error(error);
  }
};

// 取消
const handleCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    resource_type: '',
    resource_sub_type: '',
    business_type: '',
    status: '1',
    description: '',
    properties: '',
    constraints: '',
    metadata: '',
  });
};

// 生命周期
onMounted(() => {
  loadResourceList();
});
</script>

<style lang="less" scoped>
.resource-registry {
  padding: 24px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h2 {
      margin: 0;
    }
  }

  .text-danger {
    color: #ff4d4f;
  }
}
</style>
